package com.itboye.core.utils;

import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.google.gson.Gson;
import com.itboye.config.GlobalConfig;
import com.itboye.core.object.SpPublicParams;
import com.itboye.jmsfhz.app.MainApplication;
import com.itboye.jmsfhz.data.model.AvatarBeans;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

public class UploadImage {
	private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
	private ExecutorService executorService;
	private static UploadImage upload;
	//图片网络地址

	private String UploadImaeUrl=GlobalConfig.IMAGEURL_API;
String	 time = String.valueOf((int) (Math.random() * 10));

	private UploadImage() {
		executorService = Executors.newFixedThreadPool(4);
	}

	/**
	 * 单例
	 * 
	 * @return
	 */
	public static synchronized UploadImage getInstance() {
		if (upload == null) {
			upload = new UploadImage();
		}

		return upload;
	}

	public void execute(final String url, final OnUploadlistener uploadListener) {
		executorService.execute(new Runnable() {

			@Override
			public void run() {

				Handler handler = new Handler(Looper.getMainLooper()) {
					@Override
					public void handleMessage(android.os.Message msg) {
						switch (msg.what) {
						case 0:
							String resultData = msg.getData().getString("result");
							// requestCode =
							// msg.getData().getInt("requestCode");
							uploadListener.OnSuccess(resultData);
							break;
						case 1:
							String errorInfo = "上传失败";
							uploadListener.OnError(errorInfo);
							break;
						default:
							break;
						}

					}
				};

				try {
					OkHttpClient client = new OkHttpClient();
					client.setConnectTimeout(10, TimeUnit.SECONDS);
					client.setReadTimeout(10, TimeUnit.SECONDS);
					client.setWriteTimeout(10, TimeUnit.SECONDS);

					File file = new File(url);
					System.out.println("uid"+(String) SPUtils.get(MainApplication.context, null, SpPublicParams.UID, "")+"?>"+file.getName());
					// 创建请求BODY
					RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
							.addFormDataPart("uid", (String) SPUtils.get(MainApplication.context, null, SpPublicParams.UID, ""))
							.addFormDataPart("type", "4")
							.addFormDataPart("notify_id", (String) SPUtils.get(MainApplication.context, null, time, ""))
							.addFormDataPart("image", file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file)).build();

					Request request = new Request.Builder()///File/upload?access_token=ACCESS_TOKEN by565fa4facdb191
							.url(UploadImaeUrl)
							.post(requestBody).build();

					Response response = client.newCall(request).execute();
					if (!response.isSuccessful()) {
						handler.sendEmptyMessage(1);
					} else {
						String result = response.body().string();
						System.out.println("图片上传的结果" +
								""+result);

						Gson gson = new Gson();
						AvatarBeans avatarBeans = gson.fromJson(result, AvatarBeans.class);// 获取到网络端数据,多个参数
						if (avatarBeans.getCode() == 0) {
							Log.e("123","123");
							Message msg = new Message();
							msg.what = 0;
							Bundle bundle = new Bundle();
							bundle.putString("result", avatarBeans.getData().getUid());
							System.out.println("图片路径"+avatarBeans.getData().getUrl());
							System.out.println(">>>>>>>>>>>>>>>>>>>>>>图片id"+avatarBeans.getData().getUrl());
							SPUtils.put(MainApplication.context, null, SpPublicParams.URL, avatarBeans.getData().getUrl());
							msg.setData(bundle);
							handler.sendMessage(msg);
							// SPUtils.put(App.ctx,null, SPContants.AVATAR_ID,
							// avatarBeans.getData().getId());

							String url = (String) SPUtils.get(MainApplication.context, null, SPContants.AVATAR_URL, "");
							if (!url.equals("")) {
								SPUtils.remove(MainApplication.context, null, SPContants.AVATAR_URL);
							}
							SPUtils.put(MainApplication.context, null, SPContants.AVATAR_URL, avatarBeans.getData().getUrl());
						}

					}
				} catch (Exception e) {
					e.printStackTrace();

				}
			}

		});
	}

	/**
	 * 
	 * @author winter 要实现的接口
	 */

	public interface OnUploadlistener {

		public void OnSuccess(String resultData);

		public void OnError(String resultData);

	}
}
